package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 入住Service业务层处理
 * 
 * @author laoye
 * @date 2024-11-11
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    private static final AtomicInteger counter = new AtomicInteger(1);
    private static final int MAX_VALUE = 9999;
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    @Autowired
    private CheckInMapper checkInMapper;

    @Resource
    private ElderMapper elderMapper;

    @Resource
    private BedMapper bedMapper;

    @Resource
    private ContractMapper contractMapper;
    @Resource
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //首先判断这个老人有没有入住
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<Elder>();
        elderQueryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .in(Elder::getStatus, List.of(1,2,3,4));
        Elder elderIn = elderMapper.selectOne(elderQueryWrapper);
        if(ObjectUtils.isNotEmpty(elderIn)) {
            throw new ServiceException("老人已入住");
        }
        //没有则需要
        // 通过床的id查询床位是否被占用
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        if(bed.getBedStatus() == 1){
            throw new ServiceException("该床位已有人了");
        }
        // 1.更新床铺状态
        //什么时候能更新，根据id查询床位，且未入住
        //如果被占用，则不能入住
        //多线程时，防止多个老人住一张床
        LambdaUpdateWrapper<Bed> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        //乐观锁，觉得在修改是不会有人来修改，所以用条件来阻止。
        //这里set了条件，mysql有行级锁，别的线程来时就会发现status已经被改变，所以不会出现并发问题
        lambdaUpdateWrapper.eq(Bed::getId, checkInApplyDto.getCheckInConfigDto().getBedId())
                .set(Bed::getBedStatus, 1);
        int update = bedMapper.update(null, lambdaUpdateWrapper);
        if(update == 0) {
            throw new BaseException("床位已入住");
        }


        //2.新增或更新老人
        Elder elder = insertorUpdateElder(elderIn, bed, checkInApplyDto);
        //3.新增签约合同
        insertContract(elder,checkInApplyDto);
        //4.新增入住记录
        CheckIn checkIn = insertCheckIn(elder, bed, checkInApplyDto);
        //5.新增入住配置
        insertCheckInConfig(checkIn,checkInApplyDto);

    }

    /**
     * 获取入住详情id
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getDetailById(Long id) throws JsonProcessingException {
        //id是checkin的id，
        //1.查checkineldervo
        // 跟据checkinid查询老人的身份证再去查询老人详情
        CheckIn checkIn = selectCheckInById(id);

        Elder elder = elderMapper.getCheckInElderVoByIdCardNo(checkIn.getIdCardNo());
        //算出年龄
        Integer age = calculateAge(elder.getIdCardNo(), LocalDate.now());
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        checkInElderVo.setAge(age);



        //2.老人家属信息
        // 将 JSON 字符串转换为 List<Contact> 对象
        String json = elder.getRemark();
        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();

        List<ElderFamilyVo> elderFamilyVoList = objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, ElderFamilyVo.class));

        //3. 老人合同信息,通过老人id查找
        LambdaQueryWrapper<Contract> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Contract::getElderId, elder.getId());
        Contract contract = contractMapper.selectOne(queryWrapper);

        //4. 老人入住配置信息
        CheckInConfigVo checkInConfigVo = checkInConfigMapper.selectCheckInConfigByCheckInId(id);
        checkInConfigVo.setBedNumber(elder.getBedNumber());
        checkInConfigVo.setStartDate(contract.getStartDate());
        checkInConfigVo.setEndDate(contract.getEndDate());

        Map<String, Object> map = new HashMap<>();
        map.put("checkInElderVo", checkInElderVo);
        map.put("elderFamilyVoList",elderFamilyVoList);
        map.put("checkInConfigVo",checkInConfigVo);
        map.put("contract",contract);



        return map;
    }

    private  int calculateAge(String idCardNo, LocalDate currentDate) {

        if (StringUtils.isEmpty(idCardNo) || currentDate == null) {
            throw new IllegalArgumentException("出生日期和当前日期不能为空");
        }
        //把字符串转化为LocalDate类型
// 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String birthString = idCardNo.substring(6, 14);
        LocalDate birthDate = LocalDate.parse(birthString, formatter);

        // 使用 Period 类计算两个日期之间的年份差
        Period period = Period.between(birthDate, currentDate);

        // 返回年龄
        return period.getYears();
    }

    /**
     * 新增入住配置
     * @param checkIn
     * @param checkInApplyDto
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住记录
     * @param elder
     * @param bed
     * @param checkInApplyDto
     */
    private CheckIn insertCheckIn(Elder elder, Bed bed, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = BeanUtil.toBeanIgnoreError(checkInApplyDto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setIdCardNo(elder.getIdCardNo());

        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约合同
     * @param elder
     * @param dto
     */
    private void insertContract(Elder elder,CheckInApplyDto dto) {
        String contractNumber ="HT" + CodeGenerator.generateContractNumber();
        Contract contract = BeanUtil.toBeanIgnoreError(dto.getCheckInContractDto(), Contract.class);
        contract.setContractNumber(contractNumber);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contract.setStatus(0);//未生效，需要后期审核和支付后才会生效
        contract.setAgreementPath(dto.getCheckInContractDto().getAgreementPath());
        contract.setAgreementPath("287737");
        contractMapper.insert(contract);
    }

    private Elder insertorUpdateElder(Elder elderIn , Bed bed, CheckInApplyDto checkInApplyDto) {
        Elder elder = BeanUtil.toBeanIgnoreError(checkInApplyDto.getCheckInElderDto(), Elder.class);
        elder.setStatus(1);//1启用申请中
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
//        elder.setRemark(JSONUtil.formatJsonStr());
        String jsonString = JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList());
        elder.setRemark(jsonString);

        //如果传过来的elder为null则新增
        if (null == elderIn){
            //可以自动填充了
            elderMapper.insert(elder);
        }else {
            //否则更新
            elderMapper.updateById(elder);
        }
        return elder;
    }


}
